package com.heima.app.gateway.filter;

import com.heima.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.function.Consumer;

//App全局过滤器
@Component
@Slf4j
public class AuthFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();


        //2.校验当前请求路径是否是登录接口
        if (request.getPath().toString().contains("login")) {
            //3-1如果包含，直接放行
            return chain.filter(exchange);
        }

        //3.获取请求头里面的token信息
        String token = request.getHeaders().getFirst("token");


        //4.判断token是否为空
        if (StringUtils.isEmpty(token)) {
            //4-1如果为空，设置相应状态码，并返回
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //5.校验token有效性(JWT工具类)
        //5-1通过token转逆成用户信息
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        //5-2检验token的有效性
        int i = AppJwtUtil.verifyToken(claimsBody);

        //5-3判断token的状态
        if (i == 1 || i == 2) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        // 1. 获取token中的用户id
        Integer id = (Integer) claimsBody.get("id");

        // 2. 将用户id刷新到请求头上
        ServerHttpRequest newRequest = request.mutate().headers(new Consumer<HttpHeaders>() {
            @Override
            public void accept(HttpHeaders httpHeaders) {
                httpHeaders.add("userId", id.toString());
            }
        }).build();

        // 3. 刷新数据(将构建好的新请求刷新到交换器上面)
        exchange.mutate().request(newRequest).build();

        //6.放行
        return chain.filter(exchange);
    }
}
